package crawler.model;

import business.service.MongoDbFactory;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import crawler.common.LinkData;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.log4j.Logger;
import org.bson.types.ObjectId;

public class LinkModel {

    private static final String LINK_COLLECTION = "link";
    private static final Logger logger = Logger.getLogger(LinkModel.class);
    private static final Lock createLock_ = new ReentrantLock();
    private static LinkModel _instance = null;

    public static LinkModel getInstance() {
        if (_instance == null) {
            createLock_.lock();
            try {
                if (_instance == null) {
                    _instance = new LinkModel();

                }
            } finally {
                createLock_.unlock();
            }
        }
        return _instance;
    }

    public LinkModel() {
        try {
        } catch (Exception ex) {
            logger.error("LinkModel: " + ex);
        }
    }

    public List<LinkData> getListLink(int start, int limit) {
        List<LinkData> lstPost = new LinkedList<>();
        try {
            BasicDBObject basicDBObject = new BasicDBObject("created", -1);
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(LINK_COLLECTION);
            DBCursor cursor = coll.find().sort(basicDBObject);

            if (limit != -1) {
                cursor = cursor.skip(start).limit(limit);
            }

            while (cursor.hasNext()) {
                DBObject dbObject = cursor.next();
                lstPost.add(fromDB(dbObject));
            }
        } catch (Exception ex) {
            logger.error("LinkModel.getListLink: " + ex.getMessage(), ex);
        }
        return lstPost;
    }

    public LinkData getLinkById(String id) {
        try {
            BasicDBObject basicDBObject = new BasicDBObject("_id", new ObjectId(id));
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(LINK_COLLECTION);
            DBCursor cursor = coll.find(basicDBObject);
            if (cursor.hasNext()) {
                DBObject dbObject = cursor.next();
                LinkData postData = fromDB(dbObject);
                return postData;
            }
        } catch (Exception ex) {
            logger.error("PostModel.getPostById: " + ex.getMessage(), ex);
        }
        return null;
    }
    public static LinkData fromDB(DBObject dbObject){
        String objectId = ((ObjectId) dbObject.get("_id")).toString();
        String site = (String) dbObject.get("url");
        String patternId = (String) dbObject.get("patternId");
        String author = (String) dbObject.get("author");
        long created = (long) dbObject.get("created");
        String editor = (String) dbObject.get("editor");
        long updated = (long) dbObject.get("updated");
        LinkData linkData = new LinkData(objectId, site,patternId, author, created, editor, updated);
        return linkData;
    }
    public long countListLink() {
        long count = 0;
        try {
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(LINK_COLLECTION);
            count = coll.getCount();
        } catch (Exception ex) {
            logger.error("LinkModel.countListLink: " + ex.getMessage(), ex);
        }
        return count;
    }

    public boolean delete(String id) {
        try {
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(LINK_COLLECTION);
            coll.remove(new BasicDBObject("_id", new ObjectId(id)));

            return true;
        } catch (Exception ex) {
            logger.error("PostModel.deletePost: " + ex.getMessage(), ex);
        }
        return false;
    }
    
    public String addLink(LinkData postData) {
        String id = "";
        try {
            BasicDBObject basicDBObject = new BasicDBObject()
                    .append("url", postData.getUrl())
                    .append("patternId", postData.getPatternId())
                    .append("author", postData.getAuthor())
                    .append("created", postData.getCreated())
                    .append("ediotr", postData.getEditor())
                    .append("updated", postData.getUpdated());
            
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(LINK_COLLECTION);
            coll.insert(basicDBObject);
            
            ObjectId objectId = (ObjectId)basicDBObject.get( "_id" );
            id = objectId.toString();
        } catch (Exception ex) {
            logger.error("LinkModel.addLink: " + ex.getMessage(), ex);
        }
        return id;
    }
    
    public boolean updateLink(LinkData linkData) {
        try {
            BasicDBObject basicDBObject = new BasicDBObject()
                    .append("url", linkData.getUrl())
                    .append("patternId", linkData.getPatternId())
                    .append("author", linkData.getAuthor())
                    .append("created", linkData.getCreated())
                    .append("editor", linkData.getEditor())
                    .append("updated", linkData.getUpdated());

            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(LINK_COLLECTION);
            
            BasicDBObject updateDBObject = new BasicDBObject("$set", basicDBObject);
            BasicDBObject searchDBQuery = new BasicDBObject("_id", new ObjectId(linkData.getId()));
            coll.update(searchDBQuery, updateDBObject);
            return true;
        } catch (Exception ex) {
            logger.error("LinkModel.updateLink: " + ex.getMessage());
        }
        return false;
    }

    public boolean checkPostExists(String link){
        try {
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(LINK_COLLECTION);
            BasicDBObject queryDBObject = new BasicDBObject("url", link);
            DBCursor cursor = coll.find(queryDBObject);

            if(cursor.hasNext()) {
                return true;
            }
        } catch (Exception ex) {
            logger.error("PostModel.checkPostExists: " + ex.getMessage(), ex);
        }
        return false;
    }
}
